const { RateLimiterMemory } = require('rate-limiter-flexible');

// 创建内存限流器
const rateLimiter = new RateLimiterMemory({
  keyPrefix: 'rate_limit',
  points: parseInt(process.env.RATE_LIMIT) || 100, // 每分钟请求数
  duration: 60, // 60秒
  blockDuration: 300, // 超过限制后阻塞5分钟
});

// 限流中间件
const rateLimitMiddleware = async (req, res, next) => {
  try {
    const clientIp = req.ip || req.connection.remoteAddress;
    const key = `api:${clientIp}`;
    
    await rateLimiter.consume(key);
    next();
  } catch (rejRes) {
    res.status(429).json({
      error: '请求过于频繁，请稍后再试',
      retryAfter: Math.ceil(rejRes.msBeforeNext / 1000)
    });
  }
};

// API Key 验证中间件
const apiKeyAuth = (req, res, next) => {
  const apiKey = req.headers['x-api-key'] || req.query.apiKey;
  const validApiKeys = (process.env.API_KEYS || 'dev-key,production-api-key-123456,production-api-key-2024-hotspot-tracker').split(',');
  
  // 生产环境下强制验证API Key
  if (process.env.NODE_ENV === 'production') {
    if (!apiKey || !validApiKeys.includes(apiKey)) {
      return res.status(401).json({
        error: 'Invalid or missing API Key',
        timestamp: new Date().toISOString()
      });
    }
  } else if (apiKey && !validApiKeys.includes(apiKey)) {
    // 开发环境下只在提供了无效key时拒绝
    return res.status(401).json({
      error: 'Invalid API Key',
      timestamp: new Date().toISOString()
    });
  }
  
  next();
};

module.exports = {
  rateLimitMiddleware,
  apiKeyAuth
};